<?php
namespace app\admin\module;

use app\admin\util\Token;
use app\common\model\Admin;
use think\Exception;

class AdminModule{

    public static function page($uid,$pageSize=10){
        $super = Admin::where(['id'=>$uid,'is_super'=>1])->find();
        $where = [];
        if(empty($super)){
            //不是超级管理员 不能看到超级管理员的账号
            $where[] = ['is_super','<>',1];
        }
        return Admin::where($where)->with('role')->order('id','desc')->paginate($pageSize);
    }

    public static function create($data){
        $data['password'] = Token::password($data['password']);
        $exists = Admin::where(['username'=>$data['username']])->find();
        if(empty($exists)){
            Admin::create($data);
        }else{
            throw new Exception("该账号已经存在，不能重复添加");
        }
    }

    public static function update($data){
        $exists = Admin::where(['username'=>$data['username']])->where([['id','<>',$data['id']]])->find();
        if($exists){
           throw new Exception("该账号已经被占用,请更换账号");
        }
        $old = Admin::where(['id'=>$data['id']])->find();
        if($old['password'] == $data['password']){
            unset($data['password']);
        }else if(empty($data['password']) && isset($data['password'])){
            unset($data['password']);
        }else{
            if(strlen($data['password']) < 6 || strlen($data['password']) > 20){
                throw new Exception("密码6到20位");
            }
            $data['password'] = Token::password($data['password']);
        }

        Admin::update($data,['id'=>$data['id']]);
    }

    public static function del($id){
        $admin = Admin::where(['id'=>$id])->find();
        if($admin['is_super']){
            throw new Exception("该账户不能删除");
        }
        Admin::destroy($id);
    }

    public static function saveRole($id,$role){
        $exists = Admin::where(['id'=>$id,'is_super'=>1])->find();
        if($exists){
            throw new Exception("超级管理员不需要编辑角色");
        }
        Admin::update(['role_id'=>$role],['id'=>$id]);
    }
}